<template>
  <div class="cancellation-approval-page">
    <h2>取消申请审批</h2>

    <div v-if="loading" class="loading-spinner">加载中...</div>
    <div v-if="error" class="error-message">{{ error }}</div>
    <div v-if="successMessage" class="success-message">{{ successMessage }}</div>

    <section class="pending-cancellations-section">
      <h3>待审核的取消申请</h3>
      <p v-if="pendingCancellations.length === 0 && !loading">
        目前没有待审核的取消申请。
      </p>
      <div v-else class="request-list">
        <div v-for="request in pendingCancellations" :key="request.orderId || request.order_id" class="request-item">
          <div class="request-details">
            <p><strong>订单ID:</strong> {{ request.orderId || request.order_id }}</p>
            <p><strong>客户:</strong> {{ request.realName || request.real_name }} ({{ request.username || request.user_name }})</p>
            <p><strong>会议室:</strong> {{ request.roomname}}</p>
            <p><strong>预订时间:</strong> {{ formatDateTime(request.startTime || request.start_time) }} - {{ formatDateTime(request.endTime || request.end_time) }}</p>
            <p><strong>总金额:</strong> ¥{{ request.totalFee || request.total_fee }}</p>
            <p><strong>预估退款:</strong> ¥{{ (request.refundFee) }}</p>
            <p><strong>申请时间:</strong> {{ formatDateTime(request.createTime || request.request_time) }}</p>
          </div>
          <div class="request-actions">
            <button @click="handleApproveCancellation(request.orderId || request.order_id)" class="approve-button">
              批准
            </button>
            <button @click="handleRejectCancellation(request.orderId || request.order_id)" class="reject-button">
              拒绝
            </button>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useAuthStore } from '../../stores/auth.js'; // 假设员工登录使用authStore
import { getRefundableOrders, setOrderStatus, updateOrder } from '../../apis/orders.js';
import { getRoomById } from '../../apis/room.js';
import { ElMessage, ElMessageBox } from 'element-plus';

const authStore = useAuthStore();
const pendingCancellations = ref([]);
const loading = ref(false);
const error = ref(null);
const successMessage = ref(null);
const roomCache = ref({}); // 缓存会议室信息，避免重复请求

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  const date = new Date(dateTimeStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

const fetchPendingData = async () => {
  loading.value = true;
  error.value = null;
  successMessage.value = null;
  try {
    console.log('开始获取待审核的退款申请...');
    // 获取所有可退款的订单（状态为4：申请退款的订单）
    const response = await getRefundableOrders();
    console.log('获取退款申请响应:', response);
    
    if (response.code === 200) {
      const orders = response.data || [];
      console.log(`获取到 ${orders.length} 条退款申请`);
      
      if (orders.length === 0) {
        console.log('没有待审核的退款申请');
        pendingCancellations.value = [];
        return;
      }
      
      // 记录订单ID和room_id，便于调试
      orders.forEach(order => {
        console.log(`订单ID: ${order.orderId || order.order_id}, 会议室ID: ${order.roomId || order.room_id}`);
        console.log(`预估退款: ${order.refundFee || order.refund_fee}`);
      });
      
      // 获取会议室名称
      const ordersWithRoomInfo = await fetchRoomNames(orders);
      pendingCancellations.value = ordersWithRoomInfo;
    } else {
      error.value = response.msg || '获取待审核申请失败。';
      ElMessage.error(error.value);
      console.error('获取退款申请失败:', response.msg);
    }
  } catch (err) {
    console.error('获取待审核退款申请时发生错误:', err);
    if (err.response) {
      console.error('错误响应:', err.response.data);
      error.value = `获取待审核申请失败: ${err.response.data.msg || err.message}`;
    } else {
      error.value = `获取待审核申请失败: ${err.message}`;
    }
    ElMessage.error(error.value);
  } finally {
    loading.value = false;
  }
};

// 获取会议室名称并添加到订单数据中
const fetchRoomNames = async (orderList) => {
  const ordersWithRoomNames = [...orderList];
  
  // 获取所有需要查询的会议室ID
  const roomIdsToFetch = orderList
    .filter(order => {
      const roomId = order.roomId || order.room_id;
      // 过滤出需要获取名称的会议室ID（不在缓存中的）
      return roomId && !roomCache.value[roomId];
    })
    .map(order => order.roomId || order.room_id);
  
  // 批量获取会议室信息
  for (const roomId of roomIdsToFetch) {
    try {
      const response = await getRoomById(roomId);
      if (response.code === 200 && response.data) {
        // 缓存会议室信息
        roomCache.value[roomId] = response.data;
      }
    } catch (error) {
      console.error(`获取会议室ID ${roomId} 信息失败:`, error);
    }
  }
  
  // 将会议室名称添加到订单数据中
  return ordersWithRoomNames.map(order => {
    const roomId = order.roomId || order.room_id;
    const roomInfo = roomCache.value[roomId];
    
    return {
      ...order,
      roomname: roomInfo ? roomInfo.roomname : `会议室#${roomId}`
    };
  });
};

const handleApproveCancellation = async (orderId) => {
  try {
    console.log('批准退款申请，订单ID:', orderId);
    
    // 查找当前订单信息，获取退款金额
    const currentOrder = pendingCancellations.value.find(
      order => (parseInt(order.orderId || order.order_id, 10) === parseInt(orderId, 10))
    );
    
    if (!currentOrder) {
      ElMessage.error('找不到订单信息');
      return;
    }
    
    // 获取退款金额
    const refundFee = currentOrder.refundFee || currentOrder.refund_fee;
    console.log('退款金额:', refundFee);
    
    const result = await ElMessageBox.confirm(
      `您确定要批准此取消申请并退款 ¥${refundFee} 吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    loading.value = true;
    error.value = null;
    successMessage.value = null;
    
    // 确保orderId是数字类型
    const numOrderId = parseInt(orderId, 10);
    console.log('处理批准操作，转换后的订单ID:', numOrderId);
    
    // 构建更新数据，包括订单状态和退款金额
    const orderData = {
      orderId: numOrderId,
      paymentStatus: 2, // 已退款
      refundFee: refundFee
    };
    
    // 使用updateOrder函数更新订单数据
    const updateResult = await updateOrder(numOrderId, orderData);
    console.log('批准操作响应:', updateResult);
    
    if (updateResult.code === 200) {
      ElMessage.success(`退款申请已批准，退款金额: ¥${refundFee}`);
      successMessage.value = `退款申请已批准，退款金额: ¥${refundFee}`;
      // 从列表中移除已处理的申请
      pendingCancellations.value = pendingCancellations.value.filter(
        (request) => {
          const requestId = parseInt(request.orderId || request.order_id, 10);
          return requestId !== numOrderId;
        }
      );
    } else {
      error.value = updateResult.msg || '更新订单状态失败';
      ElMessage.error(error.value);
    }
  } catch (err) {
    if (err === 'cancel') {
      // 用户取消操作，不做处理
      return;
    }
    console.error('批准取消申请时发生错误:', err);
    if (err.response) {
      console.error('错误响应:', err.response.data);
      error.value = `批准取消申请失败: ${err.response.data.msg || err.message}`;
    } else {
      error.value = `批准取消申请时发生错误: ${err.message}`;
    }
    ElMessage.error(error.value);
  } finally {
    loading.value = false;
  }
};

const handleRejectCancellation = async (orderId) => {
  try {
    console.log('拒绝退款申请，订单ID:', orderId);
    
    const result = await ElMessageBox.confirm(
      '您确定要拒绝此取消申请吗？',
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    loading.value = true;
    error.value = null;
    successMessage.value = null;
    
    // 确保orderId是数字类型
    const numOrderId = parseInt(orderId, 10);
    console.log('处理拒绝操作，转换后的订单ID:', numOrderId);
    
    // 更新订单状态为已支付(1)，拒绝退款
    const updateResult = await setOrderStatus(numOrderId, 1);
    console.log('拒绝操作响应:', updateResult);
    
    if (updateResult.code === 200) {
      ElMessage.success('已拒绝退款申请');
      successMessage.value = '已拒绝退款申请';
      // 从列表中移除已处理的申请
      pendingCancellations.value = pendingCancellations.value.filter(
        (request) => {
          const requestId = parseInt(request.orderId || request.order_id, 10);
          return requestId !== numOrderId;
        }
      );
    } else {
      error.value = updateResult.msg || '拒绝退款申请失败';
      ElMessage.error(error.value);
    }
  } catch (err) {
    if (err === 'cancel') {
      // 用户取消操作，不做处理
      return;
    }
    console.error('拒绝取消申请时发生错误:', err);
    if (err.response) {
      console.error('错误响应:', err.response.data);
      error.value = `拒绝退款申请失败: ${err.response.data.msg || err.message}`;
    } else {
      error.value = `拒绝退款申请时发生错误: ${err.message}`;
    }
    ElMessage.error(error.value);
  } finally {
    loading.value = false;
  }
};

onMounted(fetchPendingData);
</script>

<style scoped>
.cancellation-approval-page {
  padding: 2rem;
  max-width: 900px;
  margin: 0 auto;
  font-family: 'Arial', sans-serif;
}

h2, h3 {
  color: #333;
  margin-bottom: 1rem;
}

.loading-spinner, .error-message, .success-message {
  padding: 1rem;
  margin-bottom: 1rem;
  border-radius: 4px;
  text-align: center;
}

.loading-spinner {
  background-color: #e0f7fa;
  color: #00796b;
}

.error-message {
  background-color: #ffebee;
  color: #c62828;
}

.success-message {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.pending-cancellations-section {
  background-color: #f9f9f9;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 1.5rem;
  margin-bottom: 2rem;
}

.request-list {
  display: grid;
  gap: 1rem;
}

.request-item {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.request-details p {
  margin: 0.3rem 0;
  color: #444;
}

.request-details strong {
  color: #222;
}

.request-actions button {
  margin-left: 0.5rem;
  padding: 0.75rem 1.25rem;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.3s ease;
}

.approve-button {
  background-color: #4CAF50; /* Green */
  color: white;
}

.approve-button:hover {
  background-color: #45a049;
}

.reject-button {
  background-color: #f44336; /* Red */
  color: white;
}

.reject-button:hover {
  background-color: #d32f2f;
}

.request-actions button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}
</style>
